package com.ylr.nio.buffer;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.SneakyThrows;
import org.junit.Test;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Arrays;

/**
 * @Classname helloworld
 * @Description TODO
 * @Date 2021/9/18 16:00
 * @Created by ylr
 */

public class bufferDemo1 {

    @SneakyThrows
    public static void main(String[] args) {
        Student student = new Student();
        student.setName("xiaoming");
        student.setAge(10);
        student.setSex("男");
        FileOutputStream fileOutputStream =
                new FileOutputStream("netty-learn/src/main/java/com/ylr/nio/stu.txt");
//        FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\ylr\\IdeaProjects\\java-code\\netty-learn\\src\\main\\java\\com\\ylr\\nio\\buffer\\stu.txt");
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(bufferedOutputStream, "utf-8"));
        bufferedWriter.write(JSON.toJSONString(student));
        bufferedWriter.write(JSON.toJSONString(student));
        bufferedWriter.write(JSON.toJSONString(student));
        bufferedWriter.write(JSON.toJSONString(student));
        bufferedWriter.write(JSON.toJSONString(student));
        bufferedWriter.write(JSON.toJSONString(student));
        bufferedWriter.write(JSON.toJSONString(student));
//        bufferedWriter.write("waqrqe");
        bufferedWriter.flush();
        bufferedWriter.close();

    }

    @SneakyThrows
    @Test
    public void Read() {

        FileChannel channel = new FileInputStream("C:\\Users\\ylr\\IdeaProjects\\java-code\\netty-learn\\src\\main\\java\\com\\ylr\\nio\\stu.txt").getChannel();

        ByteBuffer allocate = ByteBuffer.allocate(10);
        StringBuilder stringBuilder = new StringBuilder();
        while (true) {
            int read = channel.read(allocate);
            if (read<0) break;
            allocate.flip();
            while (allocate.hasRemaining()){

                // 构建一个byte数组
                byte[] content = new byte[allocate.limit()];
                // 从ByteBuffer中读取数据到byte数组中
                allocate.get(content);
                // 把byte数组的内容写到标准输出
                String s = new String(content,0,allocate.limit(),"utf-8");
//                System.out.print(s);
                stringBuilder.append(s);
            }
            allocate.clear();


        }
        System.out.println(stringBuilder);

    }


}


@Data
class Student{
    private String name;
    private Integer age;
    private String sex;

}